package com.agentframework.core.plan;

import com.agentframework.core.agent.AbstractAgent;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.util.StringUtils;

/**
 * 具有规划能力的智能体
 * @author wangjun
 **/
public abstract class PlanAgent extends AbstractAgent {

    protected Planner planner;

    protected WritePlanAction writePlanAction;

    public PlanAgent() {
        super(PlanAgent.class.getSimpleName());
        this.agentProfile = profile();
    }

    @Override
    protected AssistantMessage react() {
        if (!StringUtils.hasText(planner.getPlan().getGoal())) {
            planner.createPlan(this, getLatestMessage().getText());
        }

        while (planner.getPlan().getCurrentTask() != null) {
            Task task = planner.getPlan().getCurrentTask();
            logger.debug("ready to take Task {}", task.getTaskId());
            TaskResult result = actOnTask(task);
            planner.processTaskResult(this, result);
        }
        return null;
    }

    protected TaskResult actOnTask(Task task) {

        try {
            Message resp = llm.call(new PromptTemplate(planner.getPlanStatus().concat("\n").concat(task.getInstruction())).create(), task.getToolCallbacks());
            return new TaskResult(resp.getText(), true);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new TaskResult(e.getMessage(), false);
        }
    }

    protected abstract String profile();

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
        this.planner = applicationContext.getBean(Planner.class);
        this.writePlanAction = applicationContext.getBean(WritePlanAction.class);
    }

}
